﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Collections.Generic;

using Hangjing.Common;
using Hangjing.SQLServerDAL;
using Hangjing.Model;
using Hangjing.DBUtility;
using System.Text.RegularExpressions;
using Hangjing.WebCommon;
using Hangjing.Weixin;

/// <summary>
/// 跑腿订单详情
/// </summary>
public partial class Admin_shop_expressOrderDetail : AdminPageBase
{
    private string flag
    {
        get
        {
            object o = ViewState["flag"];
            return (o == null) ? "" : Convert.ToString(o);
        }
        set
        {
            ViewState["flag"] = value;
        }
    }

    private string SqlWhere
    {
        get
        {
            object o = ViewState["SqlWhere"];
            return (o == null) ? string.Empty : o.ToString();
        }
        set
        {
            ViewState["SqlWhere"] = value;
        }
    }


    private string orderid
    {
        get
        {
            object o = ViewState["orderid"];
            return (o == null) ? string.Empty : o.ToString();
        }
        set
        {
            ViewState["orderid"] = value;
        }
    }

    private int oid
    {
        get
        {
            object o = ViewState["oid"];
            return (o == null) ? 0 : Convert.ToInt32(o.ToString());
        }
        set
        {
            ViewState["oid"] = value;
        }
    }


    private int shopid
    {
        get
        {
            object o = ViewState["shopid"];
            return (o == null) ? 0 : Convert.ToInt32(o.ToString());
        }
        set
        {
            ViewState["shopid"] = value;
        }
    }

    /// <summary>
    /// 管理员编号
    /// </summary>
    private int uid
    {
        get
        {
            object o = ViewState["uid"];
            return (o == null) ? 0 : Convert.ToInt32(o.ToString());
        }
        set
        {
            ViewState["uid"] = value;
        }
    }


    protected void Page_Load(object sender, EventArgs e)
    {
        ValidatorSet validator = new ValidatorSet("Admin");
        validator.SetValidator();
        CheckRights("C");

        if (!IsPostBack)
        {
            //编辑
            string OrderId = HjNetHelper.GetQueryString("id");

            if (!string.IsNullOrEmpty(OrderId))
            {
                BindData(OrderId);
                hidDataId.Value = OrderId.ToString();

                string msg = "更新跑腿订单信息";
                pageType.Text = msg;
                oid = Convert.ToInt32(OrderId);
                uid = UserHelp.GetAdmin().ID;

            }
            else
            {
                pageType.Text = "新增订单";
                hidDataId.Value = "0";
            }
        }
    }

    Custorder bll = new Custorder();
    Foodlist orderfood_bll = new Foodlist();

    protected void BindData(string OrderId)
    {
        EnumHelper.OrderSourceToDropDownList(ddlsource);
        CustorderInfo info = bll.GetModel(Convert.ToInt32(OrderId));

        if (info != null)
        {

            hidDataId.Value = info.Unid.ToString();
            hidTogoId.Value = info.TogoId.ToString();
            hidUserId.Value = info.UserId.ToString();

            tbOrderId.Text = info.orderid.ToString();
            tbCustomerName.Text = info.CustomerName;
            tbUserName.Text = info.OrderRcver;
            tbTel.Text = info.OrderComm;
            tbAddress.Text = info.AddressText;


            //收件地址
            tbOrderAddress.Text = info.OrderAddress;
            tbshopauthuser.Text = info.shopauthuser;
            tbOrderAddrEx.Text = info.OrderAddrEx;


            tborderTime.Text = info.OrderDateTime.ToString();

            tbremark.Text = info.OrderAttach;

            this.lblpaymoney.Text = info.paymoney.ToString();

            tbUserId.Text = info.UserId.ToString();
            Textstatr.Text = info.SendTime.ToString();
            flag = info.OrderStatus.ToString() + "";

            WebUtility.SelectValue(ddlPaystate, info.paystate.ToString());


            tbsendstate.Text = WebUtility.TurnOrderSendState(info.sendstate.ToString());

            orderid = info.orderid;

            SqlWhere = "OrderComm ='" + info.OrderComm.ToString() + "' and custorder.unid <> " + OrderId + " ";

            this.rtpOrderlist.DataSource = bll.GetListFix(5, 1, SqlWhere, "OrderDateTime", 1);

            this.rtpOrderlist.DataBind();
            lbstatus.InnerHtml = "订单操作<font color='red'>(当前状态：" + WebUtility.TurnOrderState(info.OrderStatus.ToString()) + ")</font>";


            WebUtility.SelectValue(ddlsource, info.fromweb);



            tbshopdiscountmoney.Text = info.shopdiscountmoney.ToString();
            tbcardpay.Text = info.cardpay.ToString();
            tbPrice.Text = info.OrderSums.ToString();
            this.tbAdvance.Text = info.Advance.ToString();

            hflocalinfo.Value = info.ReveVar2;
            hftid.Value = info.TogoId.ToString();

            if (info.OrderChecker == 1)
            {
                btcheckaddress.Value = "地址已经复核";
                btcheckaddress.Disabled = true;
            }
            hfadminname.Value = UserHelp.GetAdmin().AdminName;

            damageRecordInfo damageinfo = new damageRecord().GetModel(info.orderid);
            if (damageinfo != null)
            {
                btadd.Style["display"] = "";
                btdel.Style["display"] = "";
                tbdamageRecordRemark.Text = damageinfo.remark;
                WebUtility.SelectValue(ddlresponsibleparty, damageinfo.responsibleparty);
            }

            getItem();

            shopid = info.TogoId;


            refundlink.HRef = "wechatrefund.aspx?id=" + info.Unid;
            refundlink.Style["display"] = "";


        }
    }

    protected void btSave_Click(object sender, EventArgs e)
    {
        OperateLogManager<CustorderInfo> logmanager = new OperateLogManager<CustorderInfo>(UserHelp.GetAdmin().AdminName, TableENUM.Custorder.ToString());
        CustorderInfo info = bll.GetModel(HjNetHelper.GetQueryInt("id", 0));

        CustorderInfo oldmodel = logmanager.Clone(info);

        info.OrderAttach = WebUtility.InputText(tbremark.Text);
        info.AddressText = WebUtility.InputText(tbAddress.Text);
        info.OrderSums = Convert.ToDecimal(tbPrice.Text);

        info.OrderRcver = WebUtility.InputText(tbUserName.Text);
        info.paystate = Convert.ToInt32(ddlPaystate.SelectedValue);
        info.shopdiscountmoney = Convert.ToDecimal(tbshopdiscountmoney.Text);

        info.Advance = Convert.ToDecimal(tbAdvance.Text);
        info.cardpay = Convert.ToDecimal(tbcardpay.Text);
        info.OrderComm = WebUtility.InputText(tbTel.Text);


        info.OrderAddress = WebUtility.InputText(tbOrderAddress.Text);
        info.shopauthuser = WebUtility.InputText(tbshopauthuser.Text);
        info.OrderAddrEx = WebUtility.InputText(tbOrderAddrEx.Text);



        //判断权限
        int _rs = WebUtility.checkOperator(3);
        if (_rs == 0)
        {
            AlertScript.RegScript(this.Page, this.UpdatePanel1, "alert('无操作权限','success','true',5);init();");
            return;
        }


        if (bll.Update(info) > 0)
        {
            new OrderManager().TellDeliverUpdateInfo(info);
            IList<deliverlogInfo> logs = logmanager.Compare(oldmodel, info, info.orderid);
            if (logs.Count > 0)
            {
                DataTable dt = CollectionHelper.ConvertTo(logs, "deliverlog");
                SQLHelper.SqlBulkCopyData(dt);


            }
            AlertScript.RegScript(this.Page, UpdatePanel1, "tipsWindown('更新订单','text:更新订单信息成功','250','150','true','','true','text')");
            BindData(info.Unid.ToString());

        }
        else
        {
            AlertScript.RegScript(this.Page, UpdatePanel1, "tipsWindown('更新订单','text:更新订单信息失败','250','150','true','','true','text')");
        }
    }

    /// <summary>
    /// 更新用户坐标
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void chagelocation_Click(object sender, EventArgs e)
    {
        string OrderId = HjNetHelper.GetQueryString("id");
        CustorderInfo order = bll.GetModel(OrderId);
        string latlng = "{\"ulat\":\"" + WebUtility.InputText(hidLat.Value) + "\",\"ulng\":\"" + WebUtility.InputText(this.hidLng.Value) + "\",\"slat\":\"" + WebUtility.InputText(this.hfshoplat.Value) + "\",\"slng\":\"" + WebUtility.InputText(hfshoplng.Value) + "\"}";
        WebUtility.excutesql("UPDATE dbo.Custorder SET ReveVar2 = '" + latlng + "' WHERE unid =  " + OrderId);
        //如果这个这个手机号没有此地址，要增加一个，

        EAddressInfo addrmodel = new EAddressInfo();
        addrmodel.Receiver = order.OrderRcver;
        addrmodel.Address = order.AddressText;
        addrmodel.BuildingID = 0;
        addrmodel.Phone = order.OrderComm;
        addrmodel.Mobilephone = order.OrderComm;
        addrmodel.UserID = uid;
        addrmodel.AddTime = DateTime.Now;
        addrmodel.Pri = 0;
        addrmodel.Lat = WebUtility.InputText(hidLat.Value);
        addrmodel.Lng = WebUtility.InputText(this.hidLng.Value);

        int userid = new EAddress().SaveUserAndAddress(addrmodel);


        string url = "expressOrderDetail.aspx?id=" + OrderId;
        AlertScript.RegScript(this.Page, UpdatePanel1, "alert('更新用户地址信息成功');gourl('" + url + "');");

    }

    /// <summary>
    /// 地址复核
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void checkaddress_Click(object sender, EventArgs e)
    {
        string OrderId = HjNetHelper.GetQueryString("id");

        string sql = "UPDATE dbo.Custorder SET OrderChecker = 1 ,settleuser = '" + UserHelp.GetAdmin().AdminName + "' WHERE unid = " + OrderId;
        WebUtility.excutesql(sql);

        string url = "expressOrderDetail.aspx?id=" + OrderId;
        AlertScript.RegScript(this.Page, UpdatePanel1, "alert('地址复核成功');gourl('" + url + "');");

    }


    /// <summary>
    /// 状态修改
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void updatestate_Click(object sender, EventArgs e)
    {
        string dataid = HjNetHelper.GetQueryString("id");
        Button bt = (Button)sender;

        CustorderInfo info = bll.GetModel(Convert.ToInt32(dataid));
        int newstate = Convert.ToInt32(bt.CommandArgument);

        bll.AddOrderRecord(info.orderid, newstate, UserHelp.GetAdmin().AdminName, "管理员修改订单信息:订单详细界面");

        string sql = "UPDATE dbo.Custorder SET OrderStatus = " + newstate + "  WHERE unid = " + dataid;
        WebUtility.excutesql(sql);



        switch (newstate)
        {
            case 2:
                break;
            case 3:

                bll.AddPoint(orderid);
                new OrderServiceImpl().manComplete(orderid, info.deliverid);

                break;
            case 6:
                break;
        }


        {
            NoticeHelper notice = new NoticeHelper(Context, info.deliverid.ToString());
            notice.sendOrderByDeliveryid(info.deliverid);
        }
        {
            NoticeHelper notice = new NoticeHelper(Context, info.TogoId.ToString());
            notice.send2ShopByShopid();
        }


        string url = "expressOrderDetail.aspx?id=" + dataid;
        AlertScript.RegScript(this.Page, UpdatePanel1, "alert('状态操作成功');gourl('" + url + "');");

    }


    /// <summary>
    /// 确认损单
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void adddamage_Click(object sender, EventArgs e)
    {
        string dataid = HjNetHelper.GetQueryString("id");
        string orderid = WebUtility.InputText(tbOrderId.Text);
        damageRecordInfo info = new damageRecordInfo();
        info.dId = 0;
        info.orderid = orderid;
        info.addtime = DateTime.Now;
        info.remark = WebUtility.InputText(tbdamageRecordRemark.Text);
        info.opadmin = UserHelp.GetAdmin().AdminName;
        info.responsibleparty = WebUtility.InputText(ddlresponsibleparty.SelectedValue, true);
        info.reveint1 = 0;
        info.reveint2 = 0;
        info.revevar1 = "";
        info.revevar2 = "";
        info.revevar3 = WebUtility.InputText(ddlresponsibleparty.SelectedItem.Text);

        new damageRecord().Add(info);

        string sql = "UPDATE  dbo.Custorder SET ReveInt2 = 1 WHERE unid = " + dataid;
        WebUtility.excutesql(sql);

        string url = "expressOrderDetail.aspx?id=" + dataid;
        AlertScript.RegScript(this.Page, UpdatePanel1, "alert('操作成功');gourl('" + url + "');");

    }

    /// <summary>
    /// 取消损单
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void delamage_Click(object sender, EventArgs e)
    {
        string dataid = HjNetHelper.GetQueryString("id");

        string orderid = WebUtility.InputText(tbOrderId.Text);

        string sql = " DELETE damageRecord WHERE orderid = '" + orderid + "'";

        sql += ";UPDATE  dbo.Custorder SET ReveInt2 = 0 WHERE unid = " + dataid;
        WebUtility.excutesql(sql);


        WebUtility.excutesql(sql);



        string url = "expressOrderDetail.aspx?id=" + dataid;
        AlertScript.RegScript(this.Page, UpdatePanel1, "alert('操作成功');gourl('" + url + "');");

    }



    protected void getItem()
    {
        IList<FoodlistInfo> food_list = new List<FoodlistInfo>();
        food_list = orderfood_bll.GetAllByOrderID(orderid);

        rptsubItem.DataSource = food_list;
        rptsubItem.DataBind();
    }

    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "del")
        {
            //判断权限
            int _rs = WebUtility.checkOperator(4);
            if (_rs == 0)
            {
                AlertScript.RegScript(this.Page, this.UpdatePanel1, "alert('无操作权限','success','true',5);init();");
                return;
            }
            if (orderfood_bll.DelList(e.CommandArgument.ToString()) > 0)
            {
                AlertScript.RegScript(this, UpdatePanel1, "alert('删除成功！');");

                int dataid = HjNetHelper.GetQueryInt("id", 0);
                new OrderManager().TellDeliverUpdateInfo(dataid);


                getItem();
            }
            else
            {
                AlertScript.RegScript(this, UpdatePanel1, "alert('删除失败，请重试！');");
            }
        }
    }

    protected void GridView_RowEditing(object sender, GridViewEditEventArgs e)
    {
        rptsubItem.EditIndex = e.NewEditIndex;
        getItem();
    }

    protected void GridView_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        rptsubItem.EditIndex = -1;
        getItem();
    }

    protected void GridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        //判断权限
        int _rs = WebUtility.checkOperator(3);
        if (_rs == 0)
        {
            AlertScript.RegScript(this.Page, this.UpdatePanel1, "alert('无操作权限','success','true',5);init();");
            return;
        }

        FoodlistInfo food = new FoodlistInfo();
        food.Unid = Convert.ToInt32(((Label)rptsubItem.Rows[e.RowIndex].FindControl("lb_id")).Text.Trim());
        food.FoodName = ((TextBox)rptsubItem.Rows[e.RowIndex].FindControl("tbFoodName")).Text.Trim();
        food.FCounts = Convert.ToInt32(((TextBox)rptsubItem.Rows[e.RowIndex].FindControl("tbFCounts")).Text.Trim());
        food.FoodPrice = Convert.ToDecimal(((TextBox)rptsubItem.Rows[e.RowIndex].FindControl("tbFoodPrice")).Text.Trim());
        food.OldPrice = food.FoodPrice;


        if (orderfood_bll.Update(food) > 0)
        {
            AlertScript.RegScript(Page, UpdatePanel1, "alert('编辑成功！');");
            getItem();
            int dataid = HjNetHelper.GetQueryInt("id", 0);
            new OrderManager().TellDeliverUpdateInfo(dataid);
        }
        else
        {
            AlertScript.RegScript(Page, UpdatePanel1, "alert('编辑失败，请重试！');");
        }
        rptsubItem.EditIndex = -1;
        getItem();
    }

    /// <summary>
    /// 添加商品
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void addfood_Click(object sender, EventArgs e)
    {

        int dataid = HjNetHelper.GetQueryInt("id", 0);

        FoodlistInfo food = new FoodlistInfo();
        food.Unid = 0;
        food.FoodName = WebUtility.InputText(tbFoodName1.Text);
        food.FCounts = Convert.ToInt32(WebUtility.InputText(tbFCounts1.Value));
        food.FoodPrice = Convert.ToDecimal(WebUtility.InputText(tbFoodPrice1.Value));
        food.OldPrice = food.FoodPrice;
        food.adddate = DateTime.Now;
        food.COUnid = dataid;
        food.orderid = orderid;
        food.InUse = "Y";
        food.Remark = "";
        food.TogoId = shopid;

        orderfood_bll.Add(food);
        new OrderManager().TellDeliverUpdateInfo(dataid);

        string url = "expressOrderDetail.aspx?id=" + dataid;
        AlertScript.RegScript(this.Page, UpdatePanel1, "alert('操作成功');gourl('" + url + "');");

    }

    /// <summary>
    /// 退款
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void refund_Click(object sender, EventArgs e)
    {

        string OrderId = HjNetHelper.GetQueryString("id");

        CustorderInfo info = bll.GetModel(HjNetHelper.GetQueryInt("id", 0));



        IList<WeChat_RefundLogInfo> refundlist = new WeChat_RefundLog().GetList(1, 1, "payorderid = '" + info.orderid + "'", "id", 1);
        if (refundlist.Count > 0)
        {
            AlertScript.RegScript(this.Page, this.UpdatePanel1, "alert('退款已经在处理中，可以点击查看退款记录，余额支付请在用户账号里查看','success','true',5);hideload_super();");
        }



        //判断权限
        int _rs = WebUtility.checkOperator(3);
        if (_rs == 0)
        {
            AlertScript.RegScript(this.Page, this.UpdatePanel1, "alert('无操作权限','success','true',5);init();");
            return;
        }



        bll.AddOrderRecord(info.orderid, info.OrderStatus, UserHelp.GetAdmin().AdminName, "管理员确认退款");


        string noticemsg = "";


        WebUtility.excutesql("UPDATE dbo.Custorder SET  OrderStatus= 6 WHERE unid = " + info.Unid + ";");
        apiResultInfo rs = new WeChat_Refund(info.orderid, Context).submitRefund();
        if (rs.state == 0)
        {
            noticemsg = rs.msg;
        }
        else
        {
            noticemsg = "已经提交退款申请,可点击《查询退款》查看";
        }

        new OrderStep().Add(new OrderStepInfo()
        {
            stepcode = 100,
            title = "管理员确认退款",
            subtitle = "",
            addtime = DateTime.Now,
            orderid = info.orderid,
            revevar1 = "",
            revevar2 = "0",

        });


        string url = "expressOrderDetail.aspx?id=" + info.Unid;

        AlertScript.RegScript(this.Page, this.UpdatePanel1, "alert('" + noticemsg + "','success','true',5);gourl('" + url + "');");


    }

}

